/*
 * @Description  :
 * @Version      : 1.0
 * @Author       : Shiming
 * @Date         : 2021-12-28 14:42:03
 * @LastEditors  : Shiming
 * @LastEditTime : 2022-05-18 17:32:11
 * @FilePath     : \\tms-obc-web\\src\\app\\routes\\order-management\\components\\vehicle-detail\\vehicle-detail.component.ts
 * Copyright (C) 2022 huzhenhong. All rights reserved.
 */
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STComponent } from '@delon/abc/st';
import { NzCardComponent } from 'ng-zorro-antd/card';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import format from 'date-fns/format';
import { OrderManagementService } from '../../services/order-management.service';
@Component({
  selector: 'app-supply-management-vehicle-detail',
  templateUrl: './vehicle-detail.component.html',
  styleUrls: ['./vehicle-detail.component.less', '../../../commom/less/trajectory.less']
})
export class OrderManagementVehicleDetailComponent implements OnInit {
  id = this.route.snapshot.params.id;
  @ViewChild('logSt') logSt!: STComponent;
  modalcontent: any;
  modalTitle: string = '';
  trajectory = 'car';
  operationList: any;
  mapList: any[] = []; //地图点位数据组
  pois: any[] = [];
  addressItems: any[] = []; //打点地址数据组
  warringList: any[] = []; //打点地址数据组
  abnormalList: any[] = [];
  i: any = {
    unLoadingPlaceList: [],
    billExpenseDetails: [],
    goodsInfoList: [],
    goodsResource: []
  };
  tabMap: string = 'car';
  billExpenses: any[] = []; //运费信息表格信息
  imges: any;
  attObj: any;
  totalObj: any;
  approvalLsit: any;
  isVisible = false;
  logColumns2: STColumn[] = [
    { title: '停车时间', index: 'parkBte', width: 120, className: 'text-center' },
    { title: '停车地点', index: 'parkAdr' }
  ];
  logColumns3: STColumn[] = [
    { title: '时间', index: 'warningTime' },
    { title: '异常预警类型', index: 'warningTypeLabel' }
  ];
  operateLogColums: STColumn[] = [
    { title: '内容', index: 'operationContent' },
    { title: '操作人', render: 'operator' },
    { title: '操作时间', index: 'operatorTimestamp' }
  ];
  logColumns: STColumn[] = [
    { title: '款项', index: 'expenseCodeLabel' },
    { title: '小计（元）', render: 'prices' },
    { title: '运输费（元）', render: 'price' },
    { title: '附加费（元）', render: 'surcharge' },
    { title: '支付时间', index: 'paymentTime' },
    {
      title: '支付状态',
      className: 'text-center',
      index: 'paymentStatusLabel'
    }
  ];

  constructor(
    public route: ActivatedRoute,
    private msgSrv: NzMessageService,
    public service: OrderManagementService,
    private router: Router,
    private modal: NzModalService
  ) {}

  ngOnInit(): void {
    this.initData();
    this.getTrajectory();
  }
  get logParams() {
    return { operateObject: this.i?.billCode, operateTypeList: ['3', '8'] };
  }
  initData() {
    this.service.request(this.service.$api_get_getWholeBillDetail, { id: this.id }).subscribe(res => {
      if (res) {
        this.i = res;
        this.pois = [
          {
            markerLabel: '装',
            color: 'blue',
            position: [res.startingPoint.longitude, res.startingPoint.latitude],
            title: `发货地：${res.startingPoint.province}${res.startingPoint.city}${res.startingPoint.area || ''}${
              res.startingPoint.detailedAddress
            }`,
            time: '计划出发时间：' + res.loadPlanTime
          },
          {
            markerLabel: '卸',
            color: 'red',
            position: [res.endPoint.longitude, res.endPoint.latitude],
            title: `卸货地：${res.endPoint.province}${res.endPoint.city}${res.endPoint.area}${res.endPoint.detailedAddress}`,
            time: '计划卸货时间：' + res.unloadPlanTime
          }
        ];
        this.service
          .request(this.service.$api_get_log_list, { operateObject: this.i?.billCode, operateTypeList: ['3', '8'] })
          .subscribe(res => {
            if (res) {
              let a: any = [];
              res.records.forEach((item: any) => {
                a.push({
                  value: `操作人： ${item.operator} <br /> 操作内容： ${item.operationContent}`,
                  time: item.operatorTimestamp,
                  color: 'green'
                });
              });
              this.operationList = a;
            }
          });
        this.billExpenses = this.i?.billExpenseDetails?.filter(
          (data: any) => data.expenseCode === 'PRE' || data.expenseCode === 'RECE' || data.expenseCode === 'BACK'
        );
      }
    });
    this.service.request(this.service.$api_listBillComplianceAbnormalByBillId, { id: this.id }).subscribe(res => {
      if (res) {
        this.abnormalList = res;
      }
    });
    this.service.request(this.service.$api_getAbnormalWarningByBillId, { id: this.id }).subscribe(res => {
      if (res) {
        this.warringList = res;
      }
    });
  }
  // 取消订单
  cancellation() {
    // api_get_cancelAnOrder
    this.modal.confirm({
      nzTitle: '<b>确定取消该订单吗?</b>',
      nzContent: `<b>取消后无法恢复，请确认</b>`,
      nzOnOk: () =>
        this.service.request(this.service.$api_get_cancelAnOrder, { id: this.id }).subscribe(res => {
          if (res === true) {
            this.service.msgSrv.success('操作成功！');
            this.initData();
          }
        })
    });
  }
  goBack() {
    window.history.go(-1);
  }
  // 修改订单
  changeOrder() {
    this.router.navigate(['order-management/vehicle-detailChange', this.id]);
  }
  agreement(value: any) {
    if (value === '1') {
      // this.modalTitle = '附件信息';
      // this.modalcontent = this.i?.contractContent?.contractContent;
      this.service.openURL(this.i?.contractContent?.contractFilePath);
    } else if (value === '2') {
      this.modalTitle = '补充协议';
      this.modalcontent = this.i?.supplementContent?.contractContent;
      this.isVisible = true;
    }
  }
  handleCancel() {
    this.isVisible = false;
  }
  handleOK() {
    this.isVisible = false;
  }

  goDistance(elf: any) {
    if (elf) {
      elf['elementRef'].nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' });
      // elf['elementRef'].nativeElement.className = 'target-fix'
    }
  }
  // 获取车辆轨迹
  getTrajectory() {
    this.service.request(this.service.$api_get_getTrajectory, { id: this.id }).subscribe(res => {
      if (res) {
        const points = res.trackArray;
        let list: any[] = [];
        points?.forEach((item: any) => {
          list.push({
            name: `${item.spd}`,
            lnglat: [Number((Number(item.lon) / 600000).toFixed(6)), Number((Number(item.lat) / 600000).toFixed(6))],
            time: item.gtm
          });
        });
        this.mapList = list;
        const addressItems: any[] = res.parkArray;
        if (addressItems?.length > 0) {
          addressItems.forEach(item => {
            item.parkBte = item.parkBte;
          });
          this.addressItems = [...addressItems];
        } else {
          this.addressItems = [];
        }
      }
    });
  }

  getTrajectory2() {
    this.service.request(this.service.$api_get_againGetBillTrajectoryByBillId, { id: this.id }).subscribe(res => {
      if (res) {
        const points = res.trackArray;
        let list: any[] = [];
        points?.forEach((item: any) => {
          list.push({
            name: `${item.spd}`,
            lnglat: [Number((Number(item.lon) / 600000).toFixed(6)), Number((Number(item.lat) / 600000).toFixed(6))],
            time: item.gtm
          });
        });
        this.mapList = list;
        const addressItems: any[] = res.parkArray;
        if (addressItems?.length > 0) {
          addressItems.forEach(item => {
            item.parkBte = item.parkBte;
          });
          this.addressItems = [...addressItems];
        } else {
          this.addressItems = [];
        }
      }
    });
  }

  // 获取司机轨迹
  getDriverTrajectory() {
    this.service.request(this.service.$api_get_getAppDriverPosition, { id: this.id }).subscribe(res => {
      if (res) {
        const points = res.tracks;
        let list: any[] = [];
        points?.forEach((item: any) => {
          list.push({
            name: item.hgt,
            lnglat: [Number((Number(item.lon) / 600000).toFixed(6)), Number((Number(item.lat) / 600000).toFixed(6))],
            time: item.gtm
          });
        });
        this.mapList = list || [];
        const addressItems = [...res.tracks];
        if (addressItems) {
          addressItems.forEach(item => {
            // item.parkBte = item.gtm;
            item.parkBte = item.gtm;
            item.parkAdr = item.appAdress;
          });
          this.addressItems = [...addressItems];
        } else {
          this.addressItems = [];
        }
      }
    });
  }
  trajectoryChange(event: any) {
    this.tabMap = event;
    if (event === 'car') {
      this.getTrajectory();
    } else if (event === 'driver') {
      this.getDriverTrajectory();
    }
  }
  restMap() {
    if (this.tabMap === 'car') {
      this.getTrajectory();
    } else if (this.tabMap === 'driver') {
      this.getDriverTrajectory();
    }
  }
  regetMap() {
      this.getTrajectory2();
  }
  getLocalTime(time: any) {
    if (!time) {
      return '';
    }
    return format(new Date(parseInt(time)), 'yyyy-MM-dd HH:mm:ss');
  }
}
